define(function (require, exports, module) {

    require("apps/grid");
    require("apps/easyui");

    exports.init = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid);
        var contextWindow = new $.PageWindow();

        function whenView(context, row) {
            $.post(ctx + "/app/api/message/readMessage?random=" + Math.random(),
                {'ids[0]': row.id}, function(data){
                    context.detail("消息详情", row);
                });
        }
        function whenAdd(context, href) {
            contextWindow.create({
                href: href,
                method: "message_add_save",
                title: "发送消息",
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload");
                    }
                }
            });
            contextWindow.open();
        }

        function whenReply(context, href, row){
            contextWindow.create({
                href: href + "?replyUser=" + row.tMessage.fromUser.id,
                method: "message_add_save",
                title: "回复消息",
                callback: function (status) {
                    if (status) {
                        window.location.href = ctx + "/app/api/message/postIndex";
                    }
                }
            });
            contextWindow.open();
        }

        function whenSign(context) {
            var firstSelected = context.grid.datagrid('getChecked');
            //debugger;
            if (firstSelected.length == 0) {
                $.messager.alert('信息', "请先选择一行!", 'info');
                this.grid.datagrid('clearSelections');
                return;
            }
            if (firstSelected.length > 0) {
                $.messager.confirm('确定', '确定标记为已读吗?',
                    function (result) {
                        if (result) {
                            var ids = firstSelected.map(function (item) {
                                return item.id;
                            });
                            $.post(ctx + "/app/api/message/readMessage",
                                $.utils.buildJson({ids: ids}),
                                function (json) {
                                    context.grid.datagrid("load", {});
                                    if ($.utils.isError(json)) {
                                        $.messager.alert('标记失败', json.msg, 'info');
                                    } else {
                                        $.messager.alert('信息',
                                            '标记成功', 'info');
                                    }
                                }, "JSON");
                        }
                    });
            }
        }

        var pageComponentList = new $.PageListComponent(uuid, {
            view: {
                grid: "grid",
                myToolbar: "nsdb",
                colbar: "template"
            },
            configs: {
                gridTitle: "消息列表",
                gridUrl: ctx + '/app/api/message/list',
                gridColumns: [
                    {
                        field: 'id',
                        checkbox: true
                    },
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'tMessage.sendTitle',
                        title: '消息标题',
                        width: 200,
                        align: 'left'
                    },
                    {
                        field: 'tMessage.sendContent',
                        title: '消息内容',
                        width: 200,
                        hidden:true,
                        align: 'left'
                    },
                    {
                        field: 'tMessage.messageType',
                        title: '消息类型',
                        width: 100,
                        align: 'left',
                        formatter: function (value, rowData, rowIndex) {
                            if (value == 'MESSAGE_TYPE_SYSTEM') {
                                return '系统发送';
                            } else {
                                return '私信'
                            }
                        }
                    },
                    {
                        field: 'tMessage.senderName',
                        title: '消息来源',
                        width: 100,
                        align: 'left',
                        formatter: function (value, rowData, rowIndex) {
                            if (rowData.messageType == 'MESSAGE_TYPE_SYSTEM') {
                                return '系统';
                            } else {
                                return value;
                            }
                        }
                    },
                    {
                        field: 'tMessage.sendedTime',
                        title: '消息发送时间',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: 'readTime',
                        title: '阅读时间',
                        width: 100,
                        align: 'left',
                        formatter: function (value, rowData, rowIndex) {
                            if (value) {
                                return value;
                            } else {
                                return "<a>N/A</a>";
                            }
                        }
                    }
                ]
            },
            events: {
                renderColBarBefore: function (type, row) {
                    if(type == 'reply'){
                        row.tMessage.messageType == 'MESSAGE_TYPE_USER';
                    }
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "view":
                            whenView(context, row);
                            break;
                        case "reply":
                            whenReply(context, btn.href, row);
                            break;
                        default :
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                    switch (btn.key) {
                        case "del":
                            context.del(btn.href);
                            break;
                        case "sign":
                            whenSign(context);
                            break;
                        case "add":
                            whenAdd(context, btn.href);
                            break;
                        case "search_all":
                            context.searchAll();
                            break;
                        case "search":
                            context.search(btn.href, "消息搜索", "message_search");
                            break;
                        default :
                            break;
                    }
                }
            }
        });
    };

    var USER_ITEM_TEMPLATE = '{{#.}}<div data-id="ebom-item" class="ebom-item" data-item="{{id}}"><div class="float-right">' +
        '<a href="javascript:void(0)" iconCls="fa fa-trash fa-lg" plain="true"></a>' +
        '</div><span>用户名/姓名：</span>{{userNumber}}/{{userName}}</div>{{/.}}';
    require("apps/message/page.css");
    require("apps/select");
    exports.add = function(ctx, uuid, config){
        var page = new $.PageDomFactory(uuid);
        page.getJqDom("chooseUser").gridSelect({
            textbox:page.getJqDom("selected"),
            href:ctx + "/app/api/sysMember/choose",
            method:"choose_users",
            title:"选择用户",
            setValue:function(postData){
                //检查是否已经包含该结构
                var results = [], items = [];
                page.getJqDom("ebom-item").each(function () {
                    results.push($(this).attr("data-item"));
                });
                for (var i = 0, l = postData.length; i < l; i++) {
                    if (!results.contains(postData[i].id)) {
                        items.push(postData[i]);
                        results.push(postData[i].id);
                    }
                }
                var $this = this;
                $(Mustache.render(USER_ITEM_TEMPLATE, items)).prependTo(this.options.textbox).each(function () {
                    $(this).find("a").linkbutton({
                        onClick: function () {
                            $(this).closest(".ebom-item").fadeOut(function () {
                                $(this).remove();
                                var _results = [];
                                page.getJqDom("ebom-item").each(function () {
                                    _results.push($(this).attr("data-item"));
                                });
                                if(!_results.length){
                                    $this.options.textbox.hide();
                                }
                                page.getJqDom("userIds").val(_results.join(","))
                            });
                        }
                    });
                });
                if(results.length){
                    $this.options.textbox.show();
                }
                page.getJqDom("userIds").val(results.join(","))
            }
        });
        if(config.userId){
            page.getJqDom("chooseUser").gridSelect("addValues", [{
                id:config.userId,
                userNumber:config.userNumber,
                userName:config.userName
            }])
        }

        window.message_add_save = function(win) {
            var form = page.getJqDom('form-message-add-info');
            if (!form.form('validate')) {
                return false;
            }
            win.wait("start", "保存中,请稍候.");
            var postData = form.serializeJson();
            postData.userIds = $.trim(postData.userIds);
            postData.userIds = postData.userIds.split(",");
            function send(){
                $.post(form.attr(
                        "action")
                        + "?random=" + Math.random(), $.utils.buildJson(postData),
                    function (json) {
                        win.wait("end");
                        if ($.isErrorRequest(json)) {
                            $.messager.alert('信息',
                                json.msg, 'info');
                            win.callback(false);
                        } else {
                            $.messager.alert('信息',
                                '保存成功', 'info');
                            win.callback(true);
                            win.close();
                        }
                    }, "json");
            }
            if(postData.userIds.length){
                send();
            }else{
                $.messager.confirm("确认", "未选择用户则会发送消息给所有系统用户，是否继续操作？", function(arg){
                    if(arg){
                        send();
                    }
                })
            }

        }
    };

    exports.search = function(ctx, uuid){
        var page = new $.PageDomFactory(uuid, true);
        window.message_search =  function(win) {
            win.wait("start", "搜索中,请稍候.");
            var form = $["${uuid}"].pageFactory.getJqDom("form-message-search-info");
            var postData = form.serializeJson();
            win.callback(postData);
            win.close();
        };
    }
});